$(function () {
    //格式化
    CodeMirror.defineExtension("autoIndentRange", function (from, to) {
        var cm = this;
        CodeMirror.commands["selectAll"](cm);
        var range = { from: cm.getCursor(true), to: cm.getCursor(false) };
        cm.autoFormatRange(range.from, range.to);
    });
    //codeMirror初始化
    codeMirrorInitialize();
    //事件初始化
    codeMirrorEvent();
    //初始化
    mappedStatementInitialize();
    //窗口变更事件
    resetWindowSize();
    $(window).resize(function() {
        resetWindowSize();
    });
});

function resetWindowSize() {
    //设置codeMirror高度
    var editor = $("#mappedStatement").data("codeMirror");
    var v1 = document.documentElement.clientHeight;
    var v2 = $(".dms").offset().top;
    var height = v1 - v2 - 60;
    editor.setSize(null,height);
    $(".dms .CodeMirror").css({"max-height" : height+"px"});

    //设置右侧选项卡高度
    var v2 = $(".dms").offset().top;
    var height = v1 - v2 - 60;
    $(".dms .dms-right .tab-content").height(height);
}


function codeMirrorInitialize() {
    var xmlschema = {"select":{"attrs":{"id":true,"name":"","parameterMap":"","parameterType":"","resultMap":"","resultType":["map","string","boolean","date","time","timestamp","int","long","float","double","byte","short"],"returnType":["collect","page","map","string","boolean","date","time","timestamp","int","long","float","double","byte","short"],"parameterWrapper":"","resultWrapper":"","resultSetType":["FORWARD_ONLY","SCROLL_INSENSITIVE","SCROLL_SENSITIVE","DEFAULT"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"fetchSize":"","timeout":"","flushCache":["true","false"],"useCache":["true","false"],"databaseId":"","lang":"","resultOrdered":["true","false"],"resultSets":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"association":{"attrs":{"property":true,"column":"","javaType":"","jdbcType":"","select":"","resultMap":"","typeHandler":"","notNullColumn":"","columnPrefix":"","resultSet":"","foreignColumn":"","autoMapping":["true","false"],"fetchType":["lazy","eager"]},"children":["constructor","id","result","association","collection","discriminator"]},"insert":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","useGeneratedKeys":["true","false"],"keyColumn":"","databaseId":"","lang":""},"children":["selectKey","include","trim","where","set","foreach","choose","if","bind"]},"update":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","useGeneratedKeys":["true","false"],"keyColumn":"","databaseId":"","lang":""},"children":["selectKey","include","trim","where","set","foreach","choose","if","bind"]},"mapper":{"attrs":{"namespace":""},"children":["cache-ref","cache","resultMap","parameterMap","sql","insert","update","delete","select","reference"]},"choose":{"attrs":{},"children":["when","otherwise"]},"idArg":{"attrs":{"javaType":"","column":"","jdbcType":"","typeHandler":"","select":"","resultMap":"","name":"","columnPrefix":""},"children":[]},"delete":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"databaseId":"","lang":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"when":{"attrs":{"test":true},"children":["include","trim","where","set","foreach","choose","if","bind"]},"sql":{"attrs":{"id":true,"lang":"","databaseId":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"reference":{"attrs":{"id":"","referenceId":true},"children":[]},"result":{"attrs":{"property":"","javaType":"","column":"","jdbcType":"","typeHandler":""},"children":[]},"foreach":{"attrs":{"collection":true,"item":"","index":"","open":"","close":"","separator":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"bind":{"attrs":{"name":true,"value":true},"children":[]},"trim":{"attrs":{"prefix":"","prefixOverrides":"","suffix":"","suffixOverrides":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"parameter":{"attrs":{"property":true,"javaType":"","jdbcType":"","mode":["IN","OUT","INOUT"],"resultMap":"","scale":"","typeHandler":""},"children":[]},"arg":{"attrs":{"javaType":"","column":"","jdbcType":"","typeHandler":"","select":"","resultMap":"","name":"","columnPrefix":""},"children":[]},"property":{"attrs":{"name":true,"value":true},"children":[]},"where":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"id":{"attrs":{"property":"","javaType":"","column":"","jdbcType":"","typeHandler":""},"children":[]},"parameterMap":{"attrs":{"id":true,"type":true},"children":["parameter"]},"if":{"attrs":{"test":true},"children":["include","trim","where","set","foreach","choose","if","bind"]},"case":{"attrs":{"value":true,"resultMap":"","resultType":""},"children":["constructor","id","result","association","collection","discriminator"]},"otherwise":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"include":{"attrs":{"refid":true},"children":["property"]},"cache":{"attrs":{"type":"","eviction":"","flushInterval":"","size":"","readOnly":"","blocking":""},"children":["property"]},"set":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"cache-ref":{"attrs":{"namespace":true},"children":[]},"constructor":{"attrs":{},"children":["idArg","arg"]},"collection":{"attrs":{"property":true,"column":"","javaType":"","ofType":"","jdbcType":"","select":"","resultMap":"","typeHandler":"","notNullColumn":"","columnPrefix":"","resultSet":"","foreignColumn":"","autoMapping":["true","false"],"fetchType":["lazy","eager"]},"children":["constructor","id","result","association","collection","discriminator"]},"discriminator":{"attrs":{"column":"","javaType":true,"jdbcType":"","typeHandler":""},"children":["case"]},"resultMap":{"attrs":{"id":true,"type":true,"extends":"","autoMapping":["true","false"]},"children":["constructor","id","result","association","collection","discriminator"]},"selectKey":{"attrs":{"resultType":"","statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","keyColumn":"","order":["BEFORE","AFTER"],"databaseId":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"typeAlias":{"attrs":{"alias":true,"type":true},"children":[]}};

    //  var xmlschema = {"select":{"attrs":{"id":true,"name":"","parameterMap":"","parameterType":"","resultMap":"","resultType":["map","string","boolean","date","time","timestamp","int","long","float","double","byte","short"],"returnType":["collect","page","map","string","boolean","date","time","timestamp","int","long","float","double","byte","short"],"parameterWrapper":"","resultWrapper":"","resultSetType":["FORWARD_ONLY","SCROLL_INSENSITIVE","SCROLL_SENSITIVE","DEFAULT"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"fetchSize":"","timeout":"","flushCache":["true","false"],"useCache":["true","false"],"databaseId":"","lang":"","resultOrdered":["true","false"],"resultSets":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"association":{"attrs":{"property":true,"column":"","javaType":"","jdbcType":"","select":"","resultMap":"","typeHandler":"","notNullColumn":"","columnPrefix":"","resultSet":"","foreignColumn":"","autoMapping":["true","false"],"fetchType":["lazy","eager"]},"children":["constructor","id","result","association","collection","discriminator"]},"insert":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","useGeneratedKeys":["true","false"],"keyColumn":"","databaseId":"","lang":""},"children":["selectKey","include","trim","where","set","foreach","choose","if","bind"]},"update":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","useGeneratedKeys":["true","false"],"keyColumn":"","databaseId":"","lang":""},"children":["selectKey","include","trim","where","set","foreach","choose","if","bind"]},"mapper":{"attrs":{"namespace":""},"children":["cache-ref","cache","resultMap","parameterMap","sql","insert","update","delete","select"]},"choose":{"attrs":{},"children":["when","otherwise"]},"idArg":{"attrs":{"javaType":"","column":"","jdbcType":"","typeHandler":"","select":"","resultMap":"","name":"","columnPrefix":""},"children":[]},"delete":{"attrs":{"id":true,"name":"","returnType":["boolean","int","long"],"parameterMap":"","parameterType":"","parameterWrapper":"","resultWrapper":"","batchExecute":["true","false"],"batchSize":"","timeout":"","flushCache":["true","false"],"statementType":["STATEMENT","PREPARED","CALLABLE"],"databaseId":"","lang":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"when":{"attrs":{"test":true},"children":["include","trim","where","set","foreach","choose","if","bind"]},"sql":{"attrs":{"id":true,"lang":"","databaseId":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"result":{"attrs":{"property":"","javaType":"","column":"","jdbcType":"","typeHandler":""},"children":[]},"foreach":{"attrs":{"collection":true,"item":"","index":"","open":"","close":"","separator":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"bind":{"attrs":{"name":true,"value":true},"children":[]},"trim":{"attrs":{"prefix":"","prefixOverrides":"","suffix":"","suffixOverrides":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"parameter":{"attrs":{"property":true,"javaType":"","jdbcType":"","mode":["IN","OUT","INOUT"],"resultMap":"","scale":"","typeHandler":""},"children":[]},"arg":{"attrs":{"javaType":"","column":"","jdbcType":"","typeHandler":"","select":"","resultMap":"","name":"","columnPrefix":""},"children":[]},"property":{"attrs":{"name":true,"value":true},"children":[]},"where":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"id":{"attrs":{"property":"","javaType":"","column":"","jdbcType":"","typeHandler":""},"children":[]},"parameterMap":{"attrs":{"id":true,"type":true},"children":["parameter"]},"if":{"attrs":{"test":true},"children":["include","trim","where","set","foreach","choose","if","bind"]},"case":{"attrs":{"value":true,"resultMap":"","resultType":""},"children":["constructor","id","result","association","collection","discriminator"]},"otherwise":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"include":{"attrs":{"refid":true},"children":["property"]},"cache":{"attrs":{"type":"","eviction":"","flushInterval":"","size":"","readOnly":"","blocking":""},"children":["property"]},"set":{"attrs":{},"children":["include","trim","where","set","foreach","choose","if","bind"]},"cache-ref":{"attrs":{"namespace":true},"children":[]},"constructor":{"attrs":{},"children":["idArg","arg"]},"collection":{"attrs":{"property":true,"column":"","javaType":"","ofType":"","jdbcType":"","select":"","resultMap":"","typeHandler":"","notNullColumn":"","columnPrefix":"","resultSet":"","foreignColumn":"","autoMapping":["true","false"],"fetchType":["lazy","eager"]},"children":["constructor","id","result","association","collection","discriminator"]},"discriminator":{"attrs":{"column":"","javaType":true,"jdbcType":"","typeHandler":""},"children":["case"]},"resultMap":{"attrs":{"id":true,"type":true,"extends":"","autoMapping":["true","false"]},"children":["constructor","id","result","association","collection","discriminator"]},"selectKey":{"attrs":{"resultType":"","statementType":["STATEMENT","PREPARED","CALLABLE"],"keyProperty":"","keyColumn":"","order":["BEFORE","AFTER"],"databaseId":""},"children":["include","trim","where","set","foreach","choose","if","bind"]},"typeAlias":{"attrs":{"alias":true,"type":true},"children":[]}};

    var tables = {users:["name","score","birthDate"],countries:["name","population","size"]};

    var editor =  CodeMirror.fromTextArea(document.getElementById('mappedStatement'), {
        lineNumbers: true,//显示行号
        extraKeys: {
            "Ctrl-Alt": "autocomplete",
            "F11": function(codeMirror) {
                codeMirror.setOption("fullScreen", !codeMirror.getOption("fullScreen"));
            },
            "Esc": function(cm) {
                if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
            }
        },
        mode:  "xml",// "text/x-mssql",
        styleActiveLine:true,//当前行背景高亮
        matchBrackets : true,//匹配括号
        tabSize: 4,
        indentWithTabs: true, //缩进宽度为tab键宽
        smartIndent: true, //自动缩进

        //代码折叠
        lineWrapping:true,
        foldGutter: true,
        gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],

        fullScreen:false,  //全屏模式
        theme: "idea",//主题
        hintOptions: {
            //    completeSingle : false,//解决非字符类输入问题Backspace
            tables: tables,
            schemaInfo: xmlschema
        }
    });

    // editor.setOption("hintOptions", { schemaInfo: editor.hintOptions.schemaInfo });
    editor.on("change",function (codeMirror,change) {

        var cursor =  codeMirror.getCursor();
        var token = codeMirror.getTokenAt(cursor);
        var pos =  CodeMirror.Pos(cursor.line, cursor.ch);
        codeMirror.closeHint();//防止输入的内容为非提示框中的数据
        //提示确认，选中双击，删除，换行回车
        // (change.origin == "complete" && token.type != 'tag' && token.type != "attribute") ||
        if(change.origin == "*compose" || change.origin == "+delete" || (!token.type && window.event.keyCode == 13)){
            return;
        }else if(token && token.string == "<"){ //输入左尖括号"<"
            setTimeout(function() {
                if (!codeMirror.state.completionActive)
                    codeMirror.showHint({completeSingle: false});
            }, 100);
        }else if(change.origin == "complete" && token && token.type == 'tag'){//选中标签 补全整个标签
            var pos0 = {line : pos.line,ch : pos.ch - token.string.length-1};
            //获取标签必填项
            var attrs;
            var hintOpts = codeMirror.getOption("hintOptions");
            if(hintOpts && hintOpts.schemaInfo && hintOpts.schemaInfo[token.state.tagName] && (attrs = hintOpts.schemaInfo[token.state.tagName].attrs));
            var keys = [];
            if(attrs){
                for(var key in attrs){
                    if(attrs[key] === true) keys.push(key+"=\"\"");
                }
            }
            if(keys.length > 0){
                keys.unshift(" ");
                codeMirror.replaceRange("<"+token.string+keys.join(" ")+"></"+token.string+">",pos0,pos);
                //将光标启动到第一个必填属性值内
                codeMirror.setCursor({line: pos.line, ch: pos.ch+1+keys[1].length});
            }else {
                codeMirror.replaceRange("<"+token.string+"></"+token.string+">",pos0,pos);
            }
        }else if(change.origin == "complete" && token.type == 'attribute'){//选中标签内的属性
            var hintOpts = codeMirror.getOption("hintOptions");
            var pos0 = {line : pos.line,ch : pos.ch - token.string.length-1};
            var attrOpt;
            if(hintOpts && hintOpts.schemaInfo && hintOpts.schemaInfo[token.state.tagName] && hintOpts.schemaInfo[token.state.tagName].attrs &&  (attrOpt = hintOpts.schemaInfo[token.state.tagName].attrs[token.string]) && Array.isArray(attrOpt)){
                codeMirror.replaceRange(" "+token.string+"=",pos0,pos);
                //首次调用replaceRange替换后，codeMirror不会提示属性值选项,强制调用showHint提示
                codeMirror.setCursor({line: pos.line, ch: pos.ch+1});
                setTimeout(function() {
                    codeMirror.showHint({completeSingle: false});
                }, 100);
            }else {
                codeMirror.replaceRange(" "+token.string+"=\"\" ",pos0,pos);
            }
        }else if(token.string && token.string.charAt(token.string.length - 1).match(/[a-zA-Z\s=.]/gi) && token.state.hasOwnProperty("indented")){//输入字符或者空格或者等号
            //标签内输入
            if(token.state.tagName){
                // .change.removed排除调用replaceRange替换导致再次提示.以单引号或双引号结尾的不提示
                var text = change.text && change.text[0] ? change.text[0].trim() : null;
                if (change.removed && text && (/['"]/.test(text.charAt(text.length - 1)))) return false;
                setTimeout(function() {
                    codeMirror.showHint({completeSingle: false});
                }, 100);
            }else{
                var defaultMode =  codeMirror.getOption("mode");
                if(change.origin == "complete"){
                    var hintOpts = codeMirror.getOption("hintOptions");
                    //获取最后一个空格后的字符
                    var last = token.string.match(/\s?(\S*)$/);
                    var attrOpt;
                    if(hintOpts && hintOpts.tables  &&  (attrOpt = hintOpts.tables[last[1]]) && Array.isArray(attrOpt)){
                        var pos0 = {line : pos.line,ch : last.index};
                        codeMirror.replaceRange(" "+last[0]+".",pos0,pos);
                        return false;
                    }else if(token.string.charAt(token.string.length - 1) == "."){

                    }else {
                        return false;
                    }
                }
                setTimeout(function() {
                    codeMirror.setOption('mode',"sql");
                    codeMirror.showHint({completeSingle: false});
                    setTimeout(function() {
                        codeMirror.setOption("mode",defaultMode);
                    }, 200);
                }, 100);
            }
        }else {
            codeMirror.closeHint();
        }
        return false;
    });
    //缓存codeMirror
    $("#mappedStatement").data("codeMirror",editor);
}

function codeMirrorEvent() {
    //提示
    $("#codeMirror .icon-icon-question").popover();


    //生成
    $("#codeMirror").on("click","#generate",function () {
        validateGenerateMappedStatement("生成",true);
    });

    //解析/校验
    $("#codeMirror").on("click","#validator",function () {
        validateGenerateMappedStatement("解析/校验");
    });

    //合并
/*    $("#codeMirror").on("click","#merge",function () {
        //缓存codeMirror
        var editor = $("#mappedStatement").data("codeMirror");
        var data = {
            dataSourceCodes : $("#dataSourceCodes").val(),
            namespace : $("#namespace").val(),
            sqlStatement :  editor.getValue(),
            parses : getMappedStatementApiData(),
            "operate" : "合并"
        };
        $.ajax({
            url: "/dms/merge",
            data: JSON.stringify(data),
            method: "post",
            dataType: "json",
            contentType: 'application/json',
            success: function (data) {
                renderMappedStatement(data);
                $("#dms-api-tab").trigger("click");
            }
        });
    });*/

    //执行
    $("#codeMirror").on("click","#execute",function () {
        var execute = $("#dms-execute");
        var data = {
            dataSourceCodes : $("#dataSourceCodes").val(),
            namespace : $("#namespace").val(),
            sqlStatement :  $("#mappedStatement").data("codeMirror").getValue(),
            parses : getMappedStatementApiData(),
            "operate" : "全量执行"
        };
        $.ajax({
            url: "/dms/test",
            data: JSON.stringify(data),
            method: "post",
            dataType: "json",
            contentType: 'application/json',
            success: function (data) {
                $("#dms-execute-tab").trigger("click");
                renderMappedStatement(data);
            },
            error : function (XMLHttpRequest,textStatus,errorThrown) {
                var outParameter = execute.find("textarea[name='outParameter']");
                var message = XMLHttpRequest.responseJSON ? XMLHttpRequest.responseJSON.message : XMLHttpRequest.responseText;
                var textarea = $(outParameter[0]);
                textarea.removeClass("alert-success").addClass("alert-danger");
                textarea.val(message);
            }
        });
    });

    //提交
    $("#codeMirror").on("click","#submit",function () {
        validateSubmitMappedStatement();
    });

    //全屏
    $("#codeMirror").on("click","#fullscreen",function () {
        var editor = $("#mappedStatement").data("codeMirror");
        editor.setOption("fullScreen", !editor.getOption("fullScreen"));
    });

    //格式化
    $("#codeMirror").on("click","#formatter",function () {
        var editor = $("#mappedStatement").data("codeMirror");
        CodeMirror.commands["selectAll"](editor);
        var range = { from: editor.getCursor(true), to: editor.getCursor(false) };
        editor.autoFormatRange(range.from, range.to);
        //清除标记
        cleanPopover();
    });
    //结果提示
    $("#codeMirror").on("click","#alert",function () {
        $(".codeMirror-alert-info").fadeToggle(300,"swing");
    });
    //显示关闭
    $(".codeMirror-alert-info").on("click",".close",function () {
        $(".codeMirror-alert-info").fadeOut(300,"swing");
    });
}

//生成、解析验证
function validateGenerateMappedStatement(operate,override) {
    //缓存codeMirror
    var editor = $("#mappedStatement").data("codeMirror");
    var data = {
        pattern : $("#usePattern").val(),
        dataSourceCodes : $("#dataSourceCodes").val(),
        namespace : $("#namespace").val(),
        tables : $("#tables").val(),
        methods : $("#methods").val(),
        sqlStatement : (override ? "" : editor.getValue()),
        parses : getMappedStatementApiData(),
        "operate" : operate,
    };
    $.ajax({
        url: "/dms/generateParser",
        data: JSON.stringify(data),
        method: "post",
        dataType: "json",
        contentType: 'application/json',
        success: function (data) {
            $("#dms-api-tab").trigger("click");
          renderMappedStatement(data);
        }
    });
}

//提交
function validateSubmitMappedStatement() {
    //缓存codeMirror
    var editor = $("#mappedStatement").data("codeMirror");
    var data = {
        dataSourceCodes : $("#dataSourceCodes").val(),
        namespace : $("#namespace").val(),
        sqlStatement :  editor.getValue(),
        parses : getMappedStatementApiData(),
        "operate" : "提交"
    };
    $.ajax({
        url: "/dms/submit",
        data: JSON.stringify(data),
        method: "post",
        dataType: "json",
        contentType: 'application/json',
        success: function (data) {
            renderMappedStatement(data);
        }
    });
}


function renderMappedStatement(data,index) {
    //重置标记
    resetCodeMirrorMark(data);
    //设置提示信息
    resetCodeMirrorAlertMessage(data);
    if(data.status != 'error'){
        singleTablePatternInitCodeMirrorText(data);
    }
    //解析结果
    if(data.parserResults){
        renderMappedStatementApi(data.parserResults);
        renderMappedStatementExecute(data.parserResults);
    }
    //执行结果
    if(data.executeResults){
        renderMappedStatementExecuteResult(data.executeResults,index);
    }
}


function singleTablePatternInitCodeMirrorText(data) {
    var editor = $("#mappedStatement").data("codeMirror");
    if(data && data.sqlStatement){
        editor.setValue(data.sqlStatement);
    }
}

function resetCodeMirrorAlertMessage(data) {
    if(data.message){
        var status  = {
            "error" : {type : "danger",hint:"异常"},
            "warning" :{type : "warning",hint:"警告"},
            "info" : {type :"info",hint:"通知"},
            "success" : {type :"success",hint:"成功"},
        };
        $("#codeMirror #alert").show().text(data.operate+""+status[data.status].hint).attr("class","alert "+status[data.status].type);
        var message;
        if(data.lineNumber || data.lineNumber === 0){
            message = "lineNumber: "+data.lineNumber+"; columnNumber: "+data.columnNumber+";"+data.message;
        }else {
            message = data.message;
        }
        message = message ?  message.replace(/[\r\n|\n]+/g,"</br>") : "";
        $(".codeMirror-alert-info .alert-info-message").html(message);
        $(".codeMirror-alert-info").fadeIn(300,"swing").attr("class","codeMirror-alert-info alert alert-"+status[data.status].type);

        jumpCodeMirrorScroll(data.lineNumber,data.columnNumber);
    }else {
        $("#codeMirror #alert").hide();
        $(".codeMirror-alert-info").fadeOut();
    }
}

//重置Mirror标记(清除标记、重新标记)
function resetCodeMirrorMark(data) {
    //清除标记
    cleanCodeMirrorMarkPopover();

    if(data.status != 'error' || (lineNumber !== 0 && !lineNumber)){ return ;}

    //设置标记
    var editor = $("#mappedStatement").data("codeMirror");
    var codeMirrorMark = {};
    var lastLineNumber =   editor.lastLine();
    var lineNumber = data.lineNumber <= lastLineNumber ? data.lineNumber - 1 : lastLineNumber;
    var line = editor.getLineHandle(lineNumber);
    //underline wavy red
    codeMirrorMark.mark = editor.markText(CodeMirror.Pos(lineNumber, 0),CodeMirror.Pos(lineNumber, line.text.length),{className: "codeMirror-error"});
    var $row = $($(".CodeMirror").find(".codeMirror-error").parent()[0]);
    codeMirrorMark.popover = $row;
    $row.popover({content : data.message,trigger:"hover focus"}).popover('show');
    $("#mappedStatement").data("codeMirrorMark",codeMirrorMark);
}

//清除bootstrap Popover标记的错误提示
function cleanCodeMirrorMarkPopover(){
    var codeMirrorMark = $("#mappedStatement").data("codeMirrorMark");
    if(codeMirrorMark){
        codeMirrorMark.mark.clear();
        codeMirrorMark.popover.popover("dispose");
        codeMirrorMark = null;
        $("#mappedStatement").data("codeMirrorMark",null);
    }
}

//设置滚动条滚动到错误行
function jumpCodeMirrorScroll(lineNumber,columnNumber) {
    if(lineNumber !== 0 && !lineNumber){ return ;}
    var editor = $("#mappedStatement").data("codeMirror");
    editor.setCursor({line: lineNumber, ch: columnNumber});
    var t = editor.charCoords({line: lineNumber, ch: 0},"local").top;
    var middleHeight = editor.getScrollerElement().offsetHeight / 2;
    editor.scrollTo(null, t - middleHeight - 5);
}


function mappedStatementInitialize() {
    var loaded =  $('#navbar').bootstrapNavbar("loaded");
    if(!loaded || !loaded.param || !loaded.param.id){ return ;}
    $.ajax({
        url: "/dms/getById?id="+loaded.param.id,
        method: "post",
        dataType: "json",
        contentType: 'application/json',
        success: function (data) {
           renderMappedStatement(data);
            $("#dms-api-tab").trigger("click");
        }
    });
}